<template>
  <div>
    <BasicInformation :title="title" @action="handleAction" :primary-actions="mainActions"></BasicInformation>
    <div class="add">
      <div class="common-layout">
        <el-container>
          <el-main>
            <el-row>
              <el-col :span="24">
                <div class="grid-content ep-bg-purple">
                  <h4>基本信息</h4>
                  <el-form :inline="true" :model="cgxj" :rules="rules" status-icon ref="formRef">
                    <el-form-item label="单据编号" prop="code">
                      <el-input
                          v-model="cgxj.code"
                          style="width: 240px"
                          placeholder="请输入单据编号"
                          clearable
                      />
                    </el-form-item>


                    <!-- 客户 -->
                    <!--                    <el-form-item label="供应商" prop="cid">-->
                    <!--                      <el-input-->
                    <!--                          v-model="cgsq.pro_id"-->
                    <!--                          style="width: 240px"-->
                    <!--                          placeholder="请输入客户编号"-->
                    <!--                      />-->
                    <!--                    </el-form-item>-->

                    <!-- 报价日期 -->
                    <el-form-item label="需求日期" prop="get_date">
                      <el-date-picker
                          v-model="cgxj.get_date"
                          type="date"
                          placeholder="请选择日期"
                          value-format="YYYY-MM-DD"

                      />
                    </el-form-item>
                    <!--                    :disabled-date="disabledDate"-->
                    <!-- 报价名称 -->
                    <el-form-item label="备注" prop="info">
                      <el-input
                          v-model="cgxj.info"
                          style="width: 240px"
                          placeholder="请输入备注"
                      />
                    </el-form-item>

                    <el-form-item label="交货地点" prop="address">
                      <el-input
                          v-model="cgxj.address"
                          placeholder="请交货地点"
                      />
                    </el-form-item>

                    <!-- 业务员 -->
                    <el-form-item label="业务员" prop="uid">
                      <el-select
                          v-model="cgxj.uid"
                          placeholder="请选择业务员"
                          style="width: 240px;"
                          clearable
                      >
                        <el-option
                            v-for="thisUser in userList"
                            :key="thisUser.id"
                            :label="thisUser.name"
                            :value="thisUser.id"
                        />
                      </el-select>
                    </el-form-item>


                    <!-- 部门 -->
                    <el-form-item label="部门" prop="deptId">
                      <el-select
                          v-model="cgxj.deptId"
                          placeholder="请选择部门"
                          style="width: 240px;"
                          clearable
                          @change="loadUser();cgxj.uid = ''"
                      >
                        <el-option
                            v-for="dept in departments"
                            :key="dept.value"
                            :label="dept.label"
                            :value="dept.value"
                        />
                      </el-select>
                    </el-form-item>

                    <el-form-item label="采购申请编号" prop="cgsq_code">
                      <el-input
                          v-model="cgxj.cgsq_code"
                          style="width: 240px"
                          placeholder="选择采购申请"
                          @click="dialog = true;querySource()"
                      />

                    </el-form-item>

                  </el-form>
                </div>
              </el-col>
            </el-row>
          </el-main>
        </el-container>
      </div>
    </div>
    <div>
      <div class="toolbar">
        <el-button type="primary">商品信息</el-button>
        <el-button @click="addGoodsRow">继续添加</el-button>

      </div>


      <!--TODO 商品详情-->
      <!-- 商品信息表格 -->
      <el-table :data="tableData" border style="width: 100%" class="goods-table">
        <!-- 商品编码（带必填标识的下拉框） -->
        <el-table-column label="商品编码" width="150">
          <template #header>
            <span class="required-label">商品编码</span>
          </template>
          <template #default="scope">
            <el-select
                v-model="scope.row.pcode"
                placeholder="请选择商品"
                @change="handleGoodsChange(scope.row);validatePrice(scope.row)"
                clearable
            >
              <el-option
                  v-for="item in goodsOptions"
                  :key="item.code"
                  :label="`${item.code} - ${item.name}`"
                  :value="item.code"
              />
            </el-select>
          </template>
        </el-table-column>

        <!-- 商品名称 -->
        <el-table-column label="商品名称" width="180">
          <template #default="scope">{{ scope.row.name || '-' }}</template>
        </el-table-column>

        <el-table-column label="商品型号" width="180">
          <template #default="scope">{{ scope.row.type || '-' }}</template>
        </el-table-column>

        <!-- 单位（带必填标识） -->
        <el-table-column label="单位" width="80" align="center">
          <template #header>
            <span class="required-label">单位</span>
          </template>
          <template #default="scope">{{ scope.row.uname || '件' }}</template>
        </el-table-column>

        <!-- 数量（带必填标识的输入框） -->
        <el-table-column label="数量" width="120" align="center">
          <template #header>
            <span class="required-label">数量</span>
          </template>
          <template #default="scope">
            <el-input-number
                v-model="scope.row.num"
                :min="1"
                :max="scope.row.stock"
                controls-position="right"
                style="width: 100px"
            >
            </el-input-number>
          </template>
        </el-table-column>

        <el-table-column label="建议报价" width="200" align="center">
          <template #default="scope">
            <el-input
                v-model="scope.row.price"
                placeholder="输入报价"
                @focusout="validatePrice(scope.row)"
            >
              <template #append>元</template>
            </el-input>
          </template>
        </el-table-column>

        <!--    TODO 价格-->

        <!-- 历史报价（可点击链接） -->
        <!--    <el-table-column label="历史报价" width="120" align="center">-->
        <!--      <template #default="scope">-->
        <!--        <el-link-->
        <!--          type="primary"-->
        <!--          @click="showHistory(scope.row)"-->
        <!--          v-if="scope.row.historyPrice"-->
        <!--        >-->
        <!--          {{ scope.row.historyPrice }}-->
        <!--        </el-link>-->
        <!--        <span v-else>-</span>-->
        <!--      </template>-->
        <!--    </el-table-column>-->


        <!-- 其他只读列 -->
        <el-table-column
            v-for="col in readonlyColumns"
            :key="col.prop"
            :prop="col.prop"
            :label="col.label"
            :width="col.width"
            align="center"
        />
      </el-table>

    </div>
    <div class="total-summary">
      <div class="total-label">合计</div>
      <div class="total-amount">{{ formatTotal }} + {{ cgxj.total_num }}</div>
    </div>
  </div>


  <div class="dialog">
    <el-dialog
        v-model="dialog"
        title="采购申请单"
        width="70%"
        draggable
        top="5vh"
    >
      <!-- 查询条件区域 -->
      <div class="dialog-header">
        <el-input
            v-model="searchForm.code"
            placeholder="请输入单据编号"
            style="width: 240px;margin-right: 15px"
        />

        <el-button type="primary" icon="Search" @click="querySource()">查询</el-button>
        <el-button icon="Refresh" @click="searchForm.code = '';querySource()">重置</el-button>
      </div>


      <!-- 表格区域 -->
      <el-table
          ref="multipleTableRef"
          :data="cgsqList"
          row-key="id"
          style="width: 100%"
          height="60vh"
          @row-click="handleRowClick"
          highlight-current-row
      >
        <el-table-column prop="code" label="单据编号" width="200" />
        <el-table-column prop="create_date" label="单据日期" width="200" />
        <el-table-column prop="info" label="单据主题" width="200" />
        <el-table-column prop="uid" label="业务员" width="120" />
        <el-table-column prop="closed" label="已关闭" width="100" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.closed ? 'danger' : 'success'" size="small">
              {{ scope.row.closed ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页及操作按钮 -->
      <div class="dialog-footer">
        <!-- 分页组件 -->
        <div class="pagination-wrapper">
          <el-pagination
              background
              layout="prev, pager, next"
              :total="pageInfo.total"
              :page-size="PopupsPageSize"
              :current-page="PopupsPageNo"
              @current-change="handlePageChange"
          />
        </div>
        <div class="action-buttons">
          <el-button @click="dialog = false;cgxj.cgsq_code='' ">关闭</el-button>
          <el-button type="primary" @click="dialog = false;loadData()">确定</el-button>
        </div>
      </div>
    </el-dialog>
  </div>

</template>


<script setup lang="ts">
import { ref, reactive,withKeys ,watch,computed} from 'vue';
import BasicInformation from '@/public-view/BasicInformation.vue';
import {type ComponentSize, ElMessage, type FormInstance, type FormRules, type TableInstance} from 'element-plus'
import {ElInput, ElAutoResizer, ElTableV2} from 'element-plus'
import { useRouter,useRoute } from 'vue-router';
import axios from 'axios';
import type {PubUser} from "@/types/public-cg/User.ts";
import type {CGGood, PageInfo} from "@/types/cg/Util.ts";
import type {CGXJ, CGXJInfo} from "@/types/cg/CGXJ.ts";
import {searchSource} from "@/Api/CGApi/CGServ.ts";
import type {PublicProvider} from "@/types/public-cg/provider.ts";
import type {CGSQ} from "@/types/cg/CGSQ.ts";
import request from "@/util/request.ts";
import type {CGUser} from "@/types/cw/Public.ts";

let route = useRoute()
let router=useRouter()
let code = route.query.code
let PopupsPageNo=ref(1)
let PopupsPageSize=ref(10)
let searchForm = reactive({
  code:"",
})
let uid = 1
let proList = ref<PublicProvider[]>([])
let dialog = ref(false)
let cgsqList = ref<CGSQ[]>([])

const handleHistory = (row:any) => {
  console.log('查看历史报价:', row)
}
let pageInfo = ref<PageInfo>({
  pages:0,
  pageNum:PopupsPageNo.value,
  pageSize:PopupsPageSize.value,
  total:0,
  list:null,
})

const departments = ref([
  { value: 1, label: '生产部门' },
  { value: 2, label: '销售部门'},
  { value: 3, label: '仓管部门'},
  { value: 4, label: '采购部门'},
  { value: 5, label: '财务部门'},
  { value: 10, label: '人事部门'}
])
let userList = ref<CGUser[]>([

])


let cgxj = ref<CGXJ>({
  code: "CG-20250418-0001",
  uid: '',
  info: "",
  status: 0,
  get_date:null,
  total : "",
  type:18,
})
let manager = ref<PubUser>({
  name:"testUser",
  dept:"采购部",
})

let addGoodsRow = () => {
  tableData.value.push({
    pid:'0',
    major_code:'',
    num:"0",
    name:""
  })
}


let title=ref('采购询价单11') //TODO 订单标题


let checkPassList = [1, 3 , 4 , 11]
// todo 监听按钮
const handleAction = (action:string) => {
  switch(action) {
    case 'save':
      if (checkPassList.includes(cgxj.value.status)) {
        ElMessage.error("单据无法修改");
        return;
      }
      if (code == null || ''){
        submit();
      }else {
        modi();
      }
      break
    case 'history':
      router.push('cgxj')
      break;
    case 'audit':
      getCGXJ();
      break;
    case 'source':
      dialog = true;
  }
}

// todo  按钮配置
const mainActions = ref([
  {
    name: 'save',
    label: '保存',
    type: 'primary',
    icon: 'DocumentAdd'
  },
  {
    name: 'audit',
    label: '审核',
    hidden: true
  },
  {
    name:'source',
    label: "选择源单",
  },
  {
    name: 'history',
    label: '历史单据',
    badge: 3 // 角标数字
  }

])

const rules = ref({
  get_date: [{ required: true, message: '请输入需求日期', trigger: 'blur' }],
  cgsq_code:[{required:true , message:"请输入采购申请单号",trigger:'blur'}],
  deptId:[{required : true , message:'选择部门' ,trigger : 'change'}],
  uid:[{required : true , message:'选择业务员' ,trigger : 'change'}],
})


async function querySource(){
  let res = await searchSource(searchForm.code, 'CGSQ', PopupsPageNo.value, PopupsPageSize.value)
  cgsqList.value = res.data.data.list
  console.log(cgsqList.value)
  pageInfo.value = res.data.data
}

function handlePageChange(newPage:number){
  alert(newPage)
  PopupsPageNo.value = newPage;
  querySource();
}


const multipleTableRef = ref<TableInstance>()
const currentRow = ref<CGSQ | null>(null)
const handleRowClick = (row: CGSQ) => {
  if (currentRow.value?.code === row.code) {
    // 如果点击的是当前选中的行，取消选中
    currentRow.value = null
    multipleTableRef.value?.setCurrentRow(null)
    cgxj.value.cgsq_code = ''
  } else {
    // 否则，选中当前行
    currentRow.value = row
    cgxj.value.cgsq_code = row.code
    multipleTableRef.value?.setCurrentRow(row)
  }
}


const goodsOptions = ref<CGGood[]>([])

//采购信息
// const tableData = ref([{
//   goodsCode: 0,
//   quantity: 1,
//   actualPrice: null,
//   historyPrice: '点击查看',
//   vatRate: 13,
//   taxIncludedPrice: 0
// }])

let tableData = ref<CGXJInfo[]>([

])

// 只读列配置
const readonlyColumns = [
  // { prop: 'suggestedPrice', label: '建议价格', width: 120 },
  { prop: 'tax', label: '增值税税率 (%)', width: 150 },
  { prop: 'tax_price', label: '含税单价', width: 120 },
]
//todo  商品详情拓展

// 商品选择处理
// const handleGoodsChange = (row:any) => {
//   const selected = goodsOptions.value.find(item => item.code === row.goodsCode)
//   if (selected) {
//     row.goodsName = selected.name
//     row.unit = selected.uname
//     row.vatRate = selected.tax
//     // row.suggestedPrice = selected.price || 0
//     calculateTaxPrice(row)
//   }
// }

// 商品选择处理
const handleGoodsChange = (row:any) => {
  console.log(row)
  const selected = goodsOptions.value.find(item => item.code === row.pcode)
  console.log(selected)
  if (selected) {
    row.name = selected.name
    row.uname = selected.uname
    row.pid = selected.id;
    row.tax = selected.tax
    row.type = selected.type
  } else {
    // 清空相关字段
    row.goodsName = ''
    row.unit = '件'
    row.stock = 0
    row.stock = 1
  }
}

// 价格校验
const validatePrice = (row:any) => {
  row.price = Number(row.price)
  if (isNaN(row.price) || row.price < 0){
    row.price = 0
  }
  console.log("price" ,row.price)
  row.price = row.price.toFixed(2)
  calculateTaxPrice(row)
}

// 含税价计算
const calculateTaxPrice = (row:any) => {
  if (row.price && row.tax) {
    row.tax_price = (row.price * (1 + row.tax/100)).toFixed(2)
  }
}


const totalAmount = computed(() => {
  return tableData.value.reduce((sum, row) => {
    const price = Number(row.tax_price) || 0
    const quantity = Number(row.num) || 0
    return sum + (price * quantity)
  }, 0)
})
// TODO 计算金额
// 格式化金额显示
const formatTotal = computed(() => {
  cgxj.value.total = totalAmount.value.toFixed(2)
  return `¥${totalAmount.value.toFixed(2)}`
})
// 计算数量
const totalNum = computed(() => {
  return tableData.value.reduce((sum, row) => {
    return sum + Number(row.num || 0);
  }, 0);
});
watch(totalNum, (newTotal) => {
  cgxj.value.total_num = newTotal.toString();
});




async function loadInfo(){
  let res = await request.post("basic/good/getAll")
  goodsOptions.value = res.data.data
  let providerRes = await request.post("basic/Provider/selectProviderByPage",null,{
    params:{
      "pageNo":1,
      "pageSize":10
    }
  })
  proList.value = providerRes.data.data
}
loadInfo();

async function loadUser(){
  let userRes = await request.post("per/user/selectUserByDept",{
    "dept":cgxj.value.deptId
  })
  userList.value = userRes.data.data
}
loadUser()

let formRef = ref<FormInstance>()
async function submit() {
  const formValid = await formRef.value?.validate()
  if (!formValid) return
  cgxj.value.list = tableData.value
  cgxj.value.create_id = uid
  console.log("cgxj", cgxj.value)
  let res = await request.post("cg/CGXJ/addCGXJ", cgxj.value)

  if (res.data.code == 200){
    router.push('cgxj')
  }
}


//查询商品集合  TODO
async function getCGXJ(){
  console.log("code res data")
  console.log(code)
  let res = await request.post("cg/CGXJ/getCGXJ", null , {params:{code}})
  console.log(res.data)
  cgxj.value = res.data.data
  cgxj.value.modi_id = uid.toString();
  tableData.value = cgxj.value.list
  console.log(cgxj.value)
  console.log(tableData.value)
}

if (code == null || ''){
  // todo 可获取编码
}else {
  getCGXJ()
}


async function modi(){
  alert("modi")
  console.log(tableData.value)
  cgxj.value.list = tableData.value
  console.log(cgxj.value)
  let res = await request.post("cg/CGXJ/modiCGXJ", cgxj.value ,)
  if (res.data.code == 200){
    router.push('cgxj')
  }
}

async function loadData(){
  console.log("loadDate",cgxj.value.cgsq_code)
  if (cgxj.value.cgsq_code ==''){
    return
  }else {
    let res = await request.post("cg/CGSQ/getCGSQInfo", null,{
      params:{ "code":cgxj.value.cgsq_code}
    })
    tableData.value = res.data.data
    console.log(tableData.value)
  }
}

</script>

<style scoped>
.el-row {
  margin-bottom: 20px;
}

.el-row:last-child {
  margin-bottom: 0;
}

.el-col {
  border-radius: 4px;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.required-label::after {
  content: "*";
  color: #f56c6c;
  margin-left: 4px;
}

.goods-table {
  margin-top: 20px;
}

.toolbar {
  margin-bottom: 15px;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
}

.el-table :deep(.el-input__inner) {
  text-align: center;
}
.total-summary {
  background: #fff8dc; /* 浅黄色背景 */
  padding: 12px 20px;
  display: flex;
  justify-content: flex-end;
  border: 1px solid #ebeef5;
  border-top: none;
}

.total-label {
  font-weight: 600;
  color: #606266;
  margin-right: 30px;
}

.total-amount {
  color: #f56c6c;
  min-width: 120px;
  text-align: right;
  font-family: Arial, sans-serif;
}
.action-buttons button{
  width: 200px;
  display: inline-block;
  margin: auto 100px;
}
.action-buttons{
  display: flex;
  flex-direction: row-reverse;
  padding: 0 30%;
}
.pagination-wrapper{
  margin: 0 auto;
  width: 200px;
}
</style>